<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>火火股票</title>
    <script src="./jquery.min.js"></script>
    <style>
      body {
        margin: 0;
        padding: 8px;
        background: transparent;
        font-family: 'Microsoft YaHei', Arial, sans-serif;
        overflow: hidden;
        user-select: none;
      }
      #emoji {
        font-size: 20px;
        text-align: center;
        margin-bottom: 5px;
        cursor: move;
        -webkit-app-region: drag;
      }
      #info {
        color: #666;
        font-size: 11px;
        line-height: 1.3;
        max-height: none; /* 移除固定高度限制 */
        overflow-y: auto;
        overflow-x: hidden;
      }
      .stock-item {
        margin-bottom: 2px;
        padding: 1px 3px;
        border-radius: 2px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .positive { color: #666; }
      .negative { color: #666; }
      .status {
        text-align: center;
        color: #888;
        font-size: 10px;
        margin-top: 5px;
      }
      .error { color: #ff6b6b; }
      .loading { color: #ffd43b; }
      
      /* 窗口调整手柄样式 */
      .resize-handle {
        position: fixed;
        background: rgba(255, 255, 255, 0.1);
        transition: background 0.2s;
      }
      .resize-handle:hover {
        background: rgba(255, 255, 255, 0.3);
      }
      .resize-right {
        right: 0;
        top: 0;
        width: 4px;
        height: 100%;
        cursor: ew-resize;
      }
      .resize-bottom {
        bottom: 0;
        left: 0;
        width: 100%;
        height: 4px;
        cursor: ns-resize;
      }
      .resize-corner {
        right: 0;
        bottom: 0;
        width: 12px;
        height: 12px;
        cursor: nwse-resize;
        background: rgba(255, 255, 255, 0.2);
      }
      .resize-corner:hover {
        background: rgba(255, 255, 255, 0.4);
      }
    </style>
  </head>

  <body>
    <div id="emoji" title="点击刷新数据">😀</div>
    <div id="info"></div>
    <div id="status" class="status">正在加载...</div>
    
    <!-- 窗口调整手柄 -->
    <div class="resize-handle resize-right" id="resize-right"></div>
    <div class="resize-handle resize-bottom" id="resize-bottom"></div>
    <div class="resize-handle resize-corner" id="resize-corner"></div>
  </body>
</html>
<script>
  const { ipcRenderer } = require("electron");
  const fs = require("fs");
  var ids = "";
  var idArray = [];
  var emojis = ["😀", "😁", "😂", "🤣", "🤩", "😝", "🤬", "💰"];
  var refreshInterval;
  var retryCount = 0;
  var maxRetries = 3;

  // 状态更新函数
  function updateStatus(message, type = 'normal') {
    const statusEl = $("#status");
    statusEl.removeClass('error loading').text(message);
    if (type === 'error') statusEl.addClass('error');
    if (type === 'loading') statusEl.addClass('loading');
  }

  // 改进的服务器调用函数 - 现在可以依赖主进程添加的 Referer
  const callServer = (url, callback) => {
    $.ajax({
      url: url,
      type: "get",
      timeout: 8000,
      cache: true, // 改为 true，禁止 jQuery 自动添加时间戳
      dataType: "text", // 明确指定返回类型为文本
      beforeSend: function(req) {
        // 主进程会自动添加 Referer，这里只设置其他必要的头
        req.setRequestHeader("Accept", "*/*");
        req.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
      },
      success: function (data) {
        retryCount = 0;
        updateStatus(`更新: ${new Date().toLocaleTimeString()}`);
        console.log("成功获取数据，长度:", data.length);
        callback(data);
      },
      error: function (xhr, status, error) {
        console.log("请求失败:", status, error, xhr.status);
        retryCount++;
        
        if (retryCount <= maxRetries) {
          updateStatus(`连接失败，重试 ${retryCount}/${maxRetries}`, 'error');
          setTimeout(() => callServer(url, callback), 2000 * retryCount);
        } else {
          updateStatus("网络连接失败", 'error');
          $("#info").html('<div style="color:#ff6b6b;text-align:center;">⚠️ 网络连接失败<br>请检查网络后点击表情重试</div>');
        }
      }
    });
  };

  fs.readFile("C:/gp.txt", "utf8", (err, data1) => {
    if (err) {
      console.log(err);
      const defaultConfig = "#说明: sh代表上海,sz代表深证 以此类推\n#示例：贵州茅台、中国平安、五粮液\nsh600519,sh601318,sz000858";
      
      fs.writeFile("C:/gp.txt", defaultConfig, "utf8", (writeErr) => {
        if (writeErr) {
          console.error("创建配置文件失败:", writeErr);
        }
      });
      
      alert("已创建股票配置文件 C:/gp.txt\n请编辑该文件添加股票代码，然后重启应用\n\n默认股票：贵州茅台、中国平安、五粮液");
      ipcRenderer.send('close-app');
    } else {
      ids = data1.toString();
      let _idArray = ids.split("\n");
      let validStocks = [];
      
      _idArray.forEach((element) => {
        const line = element.trim();
        if (line && !line.startsWith("#")) {
          const stocks = line.split(",").map(s => s.trim()).filter(s => s);
          validStocks = validStocks.concat(stocks);
        }
      });

      if (validStocks.length === 0) {
        updateStatus("配置文件中没有有效股票代码", 'error');
        return;
      }

      idArray = validStocks;
      ids = validStocks.join(",");
      
      console.log("已加载股票:", idArray);
      updateStatus(`已加载 ${idArray.length} 只股票`, 'loading');

      $("#info").empty();
      idArray.forEach(element => {
        $("#info").append(`<div id="${element}" class="stock-item">加载中 ${element}...</div>`);
      });

      refreshData();
      refreshInterval = setInterval(refreshData, 3000);
    }
  });

  function refreshData() {
    if (!idArray || idArray.length === 0) return;

    // 使用http协议，URL不需要额外参数
    const apiUrl = "http://hq.sinajs.cn/list=" + ids;
    
    console.log("请求URL:", apiUrl);
    
    callServer(apiUrl, function (data) {
      try {
        console.log("收到数据:", data.substring(0, 200) + "...");
        
        // 清理旧的全局变量
        idArray.forEach(code => {
          delete window['hq_str_' + code];
        });
        
        // 使用全局 eval 执行返回的 JavaScript 代码
        if (data && data.trim()) {
          try {
            // 使用 window.eval 或 (1,eval) 确保在全局作用域执行
            const globalEval = eval;
            globalEval(data);
            console.log("成功执行数据代码（全局作用域）");
            
            // 验证变量是否创建
            let createdCount = 0;
            idArray.forEach(code => {
              if (window['hq_str_' + code]) {
                createdCount++;
                console.log(`✓ 变量 hq_str_${code} 已创建`);
              } else {
                console.warn(`✗ 变量 hq_str_${code} 未创建`);
              }
            });
            console.log(`成功创建 ${createdCount}/${idArray.length} 个变量`);
            
          } catch (evalErr) {
            console.error("执行数据失败:", evalErr);
            // 如果整体执行失败，尝试逐行执行
            const dataLines = data.trim().split('\n');
            dataLines.forEach((line, index) => {
              if (line.trim()) {
                try {
                  // 使用 Function 构造函数在全局作用域执行
                  (0, eval)(line);
                  console.log(`第${index + 1}行执行成功`);
                } catch (e) {
                  console.error(`第${index + 1}行执行失败:`, line.substring(0, 50), e);
                }
              }
            });
          }
        }
        
        // 再次验证所有变量
        console.log("\n验证全局变量:");
        idArray.forEach(code => {
          const varName = 'hq_str_' + code;
          const value = window[varName];
          console.log(`${varName}:`, value ? '存在 (' + value.substring(0, 30) + '...)' : '不存在');
        });
        
        let hasValidData = false;
        
        idArray.forEach((element) => {
          try {
            // 获取股票数据变量
            const varName = 'hq_str_' + element;
            let nowdata = window[varName];
            
            console.log(`\n处理 ${element}:`);
            console.log(`  变量名: ${varName}`);
            console.log(`  数据存在: ${!!nowdata}`);
            
            // 检查数据是否存在
            if (!nowdata) {
              console.warn(`  ✗ 全局变量不存在`);
              $(`#${element}`).html(`<span style="color:#888">${element} - 无数据</span>`);
              return;
            }
            
            // 检查数据类型
            if (typeof nowdata !== 'string') {
              console.warn(`  ✗ 数据类型错误: ${typeof nowdata}`);
              $(`#${element}`).html(`<span style="color:#888">${element} - 数据类型错误</span>`);
              return;
            }
            
            // 检查是否为空字符串
            if (nowdata.trim() === '') {
              console.warn(`  ✗ 数据为空`);
              $(`#${element}`).html(`<span style="color:#888">${element} - 数据为空</span>`);
              return;
            }

            // 解析股票数据
            let _splitdata = nowdata.split(",");
            
            console.log(`  字段数量: ${_splitdata.length}`);
            
            if (_splitdata.length < 32) {
              console.warn(`  ✗ 数据字段不足: ${_splitdata.length}`);
              $(`#${element}`).html(`<span style="color:#888">${element} - 格式错误 (${_splitdata.length}字段)</span>`);
              return;
            }

            // 股票数据字段说明：
            // 0: 股票名称
            // 1: 今日开盘价
            // 2: 昨日收盘价
            // 3: 当前价格
            // 4: 今日最高价
            // 5: 今日最低价
            
            const name = _splitdata[0] || element;
            const openPrice = parseFloat(_splitdata[1]) || 0;
            const yesterdayPrice = parseFloat(_splitdata[2]) || 0;
            const currentPrice = parseFloat(_splitdata[3]) || 0;
            const highPrice = parseFloat(_splitdata[4]) || 0;
            const lowPrice = parseFloat(_splitdata[5]) || 0;

            console.log(`  ✓ 解析成功: ${name}, 当前价=${currentPrice}, 昨收=${yesterdayPrice}`);
            
            // 检查数据有效性
            if (currentPrice === 0 && yesterdayPrice === 0) {
              $(`#${element}`).html(`<span style="color:#888">${name} - 停牌或无效代码</span>`);
              return;
            }
            
            // 计算涨跌幅
            const changePercent = yesterdayPrice > 0 ? 
              ((currentPrice - yesterdayPrice) / yesterdayPrice * 100) : 0;
            const changeStr = (changePercent >= 0 ? "+" : "") + changePercent.toFixed(2) + "%";
            
            // 设置颜色
            const colorClass = changePercent >= 0 ? 'positive' : 'negative';
            
            // 更新显示
            $(`#${element}`).removeClass('positive negative').addClass(colorClass).html(
              `<strong>${name}</strong> 现:<strong>${currentPrice.toFixed(2)}</strong> ${changeStr}高:${highPrice.toFixed(2)} 低:${lowPrice.toFixed(2)} 开:${openPrice.toFixed(2)}`
            );
            
            hasValidData = true;
            
            console.log(`  ✓ ${name}: ${currentPrice} (${changeStr})`);
            
          } catch (stockErr) {
            console.error(`处理 ${element} 失败:`, stockErr);
            $(`#${element}`).html(`<span style="color:#ff6b6b">${element} - 处理失败: ${stockErr.message}</span>`);
          }
        });

        // 如果有有效数据，更新表情
        if (hasValidData) {
          $("#emoji").text(emojis[Math.floor(Math.random() * emojis.length)]);
          updateStatus(`更新成功 ${new Date().toLocaleTimeString()}`);
        } else {
          updateStatus("未获取到有效数据", 'error');
          console.error("所有股票都没有有效数据");
        }
        
      } catch (parseErr) {
        console.error("数据解析失败:", parseErr);
        updateStatus("数据解析失败", 'error');
        
        // 显示调试信息
        if (data) {
          console.log("完整数据:", data);
        }
      }
    });
  }

  $("#emoji").click(function() {
    updateStatus("手动刷新中...", 'loading');
    retryCount = 0;
    refreshData();
  });

  // 窗口大小调整功能
  let isResizing = false;
  let resizeDirection = null;
  let startX = 0;
  let startY = 0;
  let startWidth = 0;
  let startHeight = 0;

  // 右边缘调整
  $('#resize-right').on('mousedown', function(e) {
    isResizing = true;
    resizeDirection = 'right';
    startX = e.screenX;
    startWidth = window.outerWidth;
    e.preventDefault();
  });

  // 底边缘调整
  $('#resize-bottom').on('mousedown', function(e) {
    isResizing = true;
    resizeDirection = 'bottom';
    startY = e.screenY;
    startHeight = window.outerHeight;
    e.preventDefault();
  });

  // 右下角调整
  $('#resize-corner').on('mousedown', function(e) {
    isResizing = true;
    resizeDirection = 'corner';
    startX = e.screenX;
    startY = e.screenY;
    startWidth = window.outerWidth;
    startHeight = window.outerHeight;
    e.preventDefault();
  });

  // 鼠标移动事件
  $(window).on('mousemove', function(e) {
    if (!isResizing) return;

    const deltaX = e.screenX - startX;
    const deltaY = e.screenY - startY;

    if (resizeDirection === 'right') {
      const newWidth = Math.max(100, startWidth + deltaX); // 最小宽度 100px
      ipcRenderer.send('resize-window', { width: newWidth, height: window.outerHeight });
    } else if (resizeDirection === 'bottom') {
      const newHeight = Math.max(50, startHeight + deltaY); // 最小高度 50px
      ipcRenderer.send('resize-window', { width: window.outerWidth, height: newHeight });
    } else if (resizeDirection === 'corner') {
      const newWidth = Math.max(100, startWidth + deltaX);
      const newHeight = Math.max(50, startHeight + deltaY);
      ipcRenderer.send('resize-window', { width: newWidth, height: newHeight });
    }
  });

  // 鼠标释放事件
  $(window).on('mouseup', function() {
    if (isResizing) {
      isResizing = false;
      resizeDirection = null;
      // 保存窗口大小
      ipcRenderer.send('save-window-size', { 
        width: window.outerWidth, 
        height: window.outerHeight 
      });
    }
  });

  $(document).ready(function() {
    console.log("股票监控应用已启动");
    updateStatus("正在初始化...", 'loading');
    
    // 请求恢复窗口大小
    ipcRenderer.send('restore-window-size');
  });
</script>
